/**
 * 分配弹框
 */
import React, { Component } from 'react';
import { Modal, message, Radio, Button, notification } from 'antd';
import { assignDevice, getPreAssign, unbind, api as apiPaths } from '../../../services/device';
import { assignDevice as assignGroup, getPreAssign as getPreAssignGroup, unbind as unbindGroup } from '../../../services/deviceGroup';
import Pc from '../../../components/permissionControl';
import Table from './table';
import { isSuccess } from '../../../configs/error';

const RadioGroup = Radio.Group;

const styles = {
	but: {
		marginRight: '1em'
	},
	root: {
		display: 'inline'
	},
	group: {
		padding: '1em 0'
	}
};

// const nameObj = {
// 	1: '投放点',
// 	2: '运营商',
// 	3: '代理商'
// };

class AssignBox extends Component {
	constructor(props, context) {
		super(props, context);
		this.state = {
			selectedRows: [],
			target: 0,
			queryData: this.getQueryData(props),
			visible: false,
			unbindVisible: false,
			targets: []
    };
	}

	componentWillReceiveProps(nextProps) {
		if (nextProps.user !== this.props.user) {
			this.setState({
				queryData: this.getQueryData(nextProps)
			});
		}
	}

	onOk = () => {
		const { selectedRows } = this.state;
		if (selectedRows.length) {
			this.assign(selectedRows[0]);
		} else {
			message.warning('请选择分配对象');
		}
	}

	getQueryData(props) {
		return {
			creatorId: props.user.id
		};
	}

	async getPreAssign() {
		const { isGroup } = this.props;
    const res = await (isGroup ? getPreAssignGroup() : getPreAssign());
		if (isSuccess(res)) {
			this.setState({
        targets: res.data,
        target: res.data && res.data.length && res.data[0].code || 0,
			});
		}
	}

	bindVisible = () => {
		const keys = this.selectedDevcies();
		const { targets } = this.state;
		if (!keys) return;
    this.setState({ visible: true });
		if (!targets || !targets.length) this.getPreAssign();
	}

	unbindVisible = () => {
		const keys = this.selectedDevcies();
		if (!keys) return;
		this.setState({ unbindVisible: true });
	}

	selectedDevcies() {
		const { deviceIds } = this.props;
		if (!deviceIds || !deviceIds.length) {
			message.warning('请选择设备');
			return false;
		}
		return deviceIds;
	}

	async assign(id) {
		const keys = this.selectedDevcies();
		const { isGroup } = this.props;
		const { target } = this.state;

		const data = {
			deviceSnos: keys,
			assignedId: id,
			forceAssign: false,
			assignDestinationType: target
		};

		let assign = assignDevice;

		if (isGroup) {
			delete data.deviceSnos;
			data.deviceGroupIds = keys;
			assign = assignGroup;
		}
		const res = await assign({ ...data });
		if (res.code === '2000010') {
			notification.warning({
				message: res.message,
				description: '部分设备存在未分润订单，确认分配？',
				duration: 0,
				btn: <Button
					type="primary"
					onClick={async () => {
						data.forceAssign = true;
						const res2 = await assign({ ...data });
						this.handleRes(res2, '分配成功');
					}}
				>确定</Button>
			});
		} else this.handleRes(res, '分配成功');
	}

	unbind = async () => {
		const keys = this.selectedDevcies();
		const { isGroup } = this.props;

		const data = {
			deviceSnos: keys
		};

		if (isGroup) {
			delete data.deviceSnos;
			data.deviceGroupIds = keys;
		}
		const res = await (isGroup ? unbindGroup(data) : unbind(data));
		this.handleRes(res, '解绑成功');
	}

	handleRes(res, text) {
		if (isSuccess(res)) {
			const { success } = this.props;
			message.success(text);
			this.setState({ visible: false, unbindVisible: false });
			if (success) success();
		}
	}

	render() {
		const { isGroup } = this.props;
		const { selectedRows, target, queryData, visible, unbindVisible, targets } = this.state;
    // const name = nameObj[target];
    const activeTarget = targets.find(item => item.code === target);
    const name = activeTarget && activeTarget.desc || '';

		return (
			<Pc mode="permissionUrl" level={2}>
				<div style={styles.root}>
					<Button
						style={styles.but}
						onClick={this.bindVisible}
						icon="check-circle-o"
						className="opt-but"
						permissionUrl={apiPaths.assignDevice}
					>分配</Button>
					<Button
						style={styles.but}
						onClick={this.unbindVisible}
						icon="close-circle-o"
						className="opt-but"
						permissionUrl={apiPaths.unbind}
					>解绑</Button>
					<Modal onCancel={() => this.setState({ visible: false })} visible={visible} onOk={this.onOk}>
						<RadioGroup onChange={e => this.setState({ target: e.target.value, selectedRows: [] })} value={target} style={styles.group}>
							{targets.map(t => <Radio value={t.code}>{t.desc}</Radio>)}
						</RadioGroup>
						<Table
							target={target}
							queryData={queryData}
							rowSelection={{
								type: 'radio',
								onChange: (key) => this.setState({ selectedRows: key }),
								selectedRowKeys: selectedRows
							}}
							rowKey="id"
						/>
					</Modal>
					<Modal
						onCancel={() => this.setState({ unbindVisible: false })}
						visible={unbindVisible}
						onOk={this.unbind}
						title="解绑设备"
					>
						<p>是否确认解除所选设备{isGroup ? '组' : ''}与{name}的绑定？</p>
						<p>解除绑定后，{name}将无法使用{isGroup ? '该组内' : '所选'}的所有设备。</p>
					</Modal>
				</div>
			</Pc>
		);
	}
}

export default AssignBox;
